class CommentsController < ApplicationController
	
	# Called when creating a direct reply to a previous comment
	def new
		@document = Document.find(params[:document_id])
		@comment = @document.comments.build(parent_id: params[:parent_id])
	end
	
	# Also called by the form in the document detail page
	def create
		document = Document.find(params[:document_id])
		
		params[:comment][:created_by] = current_user.id
		params[:comment][:owner] = current_user
		
		comment = document.comments.build(params[:comment])
		save_successful = comment.save
		if save_successful
			save_successful &= create_default_owner_permissions(comment, comment.owner)
		end
		
		respond_to do |type|
			if save_successful
				type.html { redirect_to(document, flash: { success: t('comment.create.success') })}
			else
				type.html { redirect_to(document, flash: { failure: t('comment.create.failure') })}
			end
		end
	end
	
	def edit
		@document = Document.find(params[:document_id])
		@comment = @document.comments.find(params[:id])
	end
	
	def update
		comment = Comment.find(params[:id])		
		params[:comment][:updated_by] = current_user.id		
		comment.update_attributes(params[:comment])
		
		document = comment.document
		respond_to do |type|
			if comment.save
				type.html { redirect_to(document, flash: { success: t('comment.update.success') })}
			else
				type.html { redirect_to(document, flash: { failure: t('comment.update.failure') })}
			end
		end
	end
	
	def destroy
		comment = Comment.find(params[:id])
		document = comment.document
		comment.destroy
		redirect_to document, flash: { success: t('comment.destroy.success') }
	end
	
end
